package yu.com.time.calclator

import yu.com.time.toDate
import yu.com.time.toLocalDateTime
import yu.com.time.unit.DateUnit
import yu.com.time.unit.DateUnit.*
import java.time.LocalDate
import java.time.LocalDateTime
import java.time.temporal.ChronoUnit


/**
 * java.sql.Date日期计算器
 * created zpf on 2018/10/23 0023
 * @param origDate 原始日期
 * @param unit     时间计算单位
 */
open class DateCalculator(val origDate: java.sql.Date, val unit: DateUnit) : Calculator<DateCalculator, java.util.Date>, java.sql.Date(origDate.time) {

    /**jdk8本地日期*/
    private val localDate: LocalDate = origDate.toLocalDate()
    /**jdk8本地日期时间*/
    private val localDateTime: LocalDateTime = origDate.toLocalDateTime()


    override fun plus(addition: Long): DateCalculator {
        val time = when (unit) {
            YEAR -> localDate.plusYears(addition).toDate()
            MONTH -> localDate.plusMonths(addition).toDate()
            WEEK -> localDate.plusWeeks(addition).toDate()
            DAY -> localDate.plusDays(addition).toDate()
        }
        return DateCalculator(time, unit)
    }

    override fun minus(subtraction: java.util.Date): Long {
        val refer = subtraction.toLocalDateTime()
        return when (unit) {
            YEAR -> refer.until(localDateTime, ChronoUnit.YEARS)
            MONTH -> refer.until(localDateTime, ChronoUnit.MONTHS)
            WEEK -> refer.until(localDateTime, ChronoUnit.WEEKS)
            DAY -> refer.until(localDateTime, ChronoUnit.DAYS)
        }
    }
}